<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购订单编号">
              <a-input placeholder="请输入采购订单编号" v-model="queryParam.code"></a-input>
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购订单状态">
              <j-dict-select-tag
                type="list"
                v-model="queryParam.status"
                dictCode="buss_material_procurement_status"
                placeholder="请选择采购订单状态"
              />
            </a-form-item>
          </a-col>

          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="采购订单制单人">
              <j-dict-select-tag
                placeholder="请选择采购订单制单人"
                v-model="queryParam.createBy"
                dictCode="sys_user,realname,id,org_code='A03A01A01'"
              />

            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :xl="4" :lg="6" :md="6" :sm="6">
            <a-form-item label="起始日期">
              <a-date-picker
                type="ge"
                v-model="queryParam.createTimeBg"
                :format="dateFormat"
                :valueFormat="dateFormat"
                @change="changeDate"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <a-form-item label="截止日期">
              <a-date-picker
                type="le"
                v-model="queryParam.createTimeEd"
                :format="dateFormat"
                :valueFormat="dateFormat"
                @change="changeDate"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="7" :md="8" :sm="24">
            <span style="float: left; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <!-- <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>-->
              <!-- <a @click="handleToggleSearch" style="margin-left: 8px">-->
              <!-- {{ toggleSearchStatus ? '收起' : '展开' }}-->
              <!-- <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>-->
              <!-- </a>-->
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('原料采购订单')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!--      &lt;!&ndash; 高级查询区域 &ndash;&gt;-->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <!--      <a-dropdown v-if="selectedRowKeys.length > 0">-->
      <!--        <a-menu slot="overlay">-->
      <!--          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>-->
      <!--        </a-menu>-->
      <!--        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>-->
      <!--      </a-dropdown>-->
    </div>
    <div></div>
    <!-- table区域-begin -->
    <div>
      <a-table
        ref="table"
        size="middle"
        bordered
        :rowKey="
          (record, index) => {
            return index
          }
        "
        class="j-table-force-nowrap1"
        :scroll="{ x: true }"
        :columns="table1.columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text, record">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            :preview="record.id"
            height="25px"
            alt=""
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a @click="handleDetail(record)">详情</a>
          <!--          <a @click="handleEdit(record)">编辑</a>-->
          <!--          <a-divider type="vertical" />-->
          <!--          <a-dropdown>-->
          <!--            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>-->
          <!--            <a-menu slot="overlay">-->
          <!--              <a-menu-item>-->
          <!--                <a @click="handleDetail(record)">详情</a>-->
          <!--              </a-menu-item>-->
          <!--              <a-menu-item>-->
          <!--                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.procurementId)">-->
          <!--                  <a>删除</a>-->
          <!--                </a-popconfirm>-->
          <!--              </a-menu-item>-->
          <!--            </a-menu>-->
          <!--          </a-dropdown>-->
        </span>
      </a-table>
    </div>
    <buss-storage-notice-modal ref="modalForm" @ok="modalFormOk" />

    <!-- <buss-material-procurement-arrival-modal
      ref="modalForm"
      @ok="modalFormOk"
    ></buss-material-procurement-arrival-modal> -->
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import bussMaterialProcurementArrivalModal from './modules/BussMaterialProcurementArrivalModal.vue'
import { deleteAction, downFile, getAction, getFileAccessHttpUrl } from '@/api/manage'
import '@/assets/less/TableExpand.less'
import moment from 'dayjs'
import TslSimpleQuery from '@comp/tsl/TslSimpleQuery.vue'
import TslSettingCloumns from '@comp/tsl/TslSettingCloumns.vue'
import BussStorageNoticeModal from '../storehouse/modules/BussStorageNoticeModal'

export default {
  name: 'BussMaterialProcurementArrivalList',
  mixins: [JeecgListMixin],
  components: {
    bussMaterialProcurementArrivalModal,
    TslSimpleQuery,
    TslSettingCloumns,
    BussStorageNoticeModal,
  },
  data() {
    return {
      description: '采购到货',
      dateFormat: 'YYYY-MM-DD',
      moment,
      disableMixinCreated: true,
      isOpenSettingColumns: true,
      queryParam: {
        createTimeBg: '2024-10-01',
        createTimeEd: '2024-10-31',
      },
      ignoreColumns: ['abc'],
      // 表头
      table1: {
        selectedRowKeys: [],
        selectionRows: [],
        loading: false,
        columns: [
          {
            title: '#',
            dataIndex: '',
            key: 'rowIndex',
            width: 60,
            align: 'center',
            customRender: function (t, r, index) {
              return parseInt(index) + 1
            },
          },
          {
            title: '采购订单编号',
            align: 'center',
            dataIndex: 'code',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (index > 0 && record.code === this.dataSource[index - 1].code) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter((item) => item.code === record.code).length
              }
              return obj
            },
          },
          {
            title: '供应商名称',
            align: 'center',
            dataIndex: 'supplierName',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (index > 0 && record.code === this.dataSource[index - 1].code) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter((item) => item.code === record.code).length
              }
              return obj
            },
          },
          {
            title: '物料编号',
            align: 'center',
            dataIndex: 'materialCode',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          {
            title: '物料名称',
            align: 'center',
            dataIndex: 'materialName',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          {
            title: '规格',
            align: 'center',
            dataIndex: 'spec',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          {
            title: '采购数量',
            align: 'center',
            dataIndex: 'procurementNum',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          {
            title: '单位',
            align: 'center',
            dataIndex: 'meUnit_dictText',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          {
            title: '已入库数量',
            align: 'center',
            dataIndex: 'arrivalNum',
            customRender: (text, record, index) => {
              const sanitizedText = this.sanitizeHTML(text)
              const obj = {
                children: [
                  h('div', {
                    domProps: {
                      innerHTML: text, // 直接使用 HTML 字符串
                    },
                  }),
                ],
                attrs: {},
              }
              // 判断是否需要合并行
              if (
                index > 0 &&
                record.code === this.dataSource[index - 1].code &&
                record.seq === this.dataSource[index - 1].seq
              ) {
                obj.attrs.rowSpan = 0
              } else {
                obj.attrs.rowSpan = this.dataSource.filter(
                  (item) => item.code === record.code && item.seq === record.seq
                ).length
              }
              return obj
            },
          },
          // {
          //   title: '单位',
          //   align: 'center',
          //   dataIndex: 'meUnit_dictText',
          //   scopedSlots: { customRender: 'htmlSlot' },
          // },

          {
            title: '入库单号',
            align: 'center',
            dataIndex: 'noticeCode',
            scopedSlots: { customRender: 'htmlSlot' },
          },
          // {
          //   title: '收货数量',
          //   align: 'center',
          //   dataIndex: 'arrivalNum',
          //   scopedSlots: { customRender: 'htmlSlot' },
          // },

          {
            title: '详细收货数量',
            align: 'center',
            dataIndex: 'actualNum',
            scopedSlots: { customRender: 'htmlSlot' },
          },
          // {
          //   title: '单位',
          //   align: 'center',
          //   dataIndex: 'meUnit',
          //   scopedSlots: { customRender: 'htmlSlot' },
          // },
          {
            title: '仓库编号',
            align: 'center',
            dataIndex: 'erpWarehouseCode',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          {
            title: '库位编号',
            align: 'center',
            dataIndex: 'erpLocationCode',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          {
            title: '批次号',
            align: 'center',
            dataIndex: 'batchNum',
            scopedSlots: { customRender: 'htmlSlot' },
          },
          {
            title: '物料批号',
            align: 'center',
            dataIndex: 'materialLotNum',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          {
            title: '入库日期',
            align: 'center',
            dataIndex: 'warehouseDate',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          {
            title: '收货人',
            align: 'center',
            dataIndex: 'noticeOrderCreateBy',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          {
            title: '质检状态',
            align: 'center',
            dataIndex: 'qcStatus_dictText',
            scopedSlots: { customRender: 'htmlSlot' },
          },

          // {
          //   title: '未到货数量',
          //   align: 'center',
          //   dataIndex: 'originalNum',
          //   // scopedSlots: { customRender: 'htmlSlot' },
          //   customRender: (text, record, index) => {
          //     // Provide default value if baseValue is missing
          //     if (record.arrivalNum) {
          //       return record.procurementNum - record.arrivalNum
          //     }
          //     return record.procurementNum
          //   },
          // },
          {
            title: '操作',
            dataIndex: 'action',
            align: 'center',
            fixed: 'right',
            width: 150,
            customRender: (text, record, index) => {
              const obj = {
                children: [<a onClick={() => this.handleDetail(record)}>查看详情</a>],
                attrs: {},
              }

              return obj
            },
            // scopedSlots: { customRender: 'action' },
          },
        ],
        dataSource: [],
        dataSourceBack: [],
        ipagination: {
          current: 1,
          pageSize: 30,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + '-' + range[1] + ' 共' + total + '条'
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0,
        },
      },
      url: {
        list: '/business/bussMaterialProcurement/arrayInfo',
        delete: '/business/bussMaterialProcurement/delete',
        deleteBatch: '/business/bussMaterialProcurement/deleteBatch',
        exportXlsUrl: '/business/bussMaterialProcurement/exportXls',
        importExcelUrl: '/business/bussMaterialProcurement/importExcel',
        proclist: '/business/bussMaterialProcurement/page/list',
        materialReceiveList: '/business/bussMaterialProcurement/materialReceiveList',
      },
      dictOptions: {},
      superFieldList: [],
    }
  },
  created() {
    this.getSuperFieldList()
    this.loadData()
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    },
  },
  methods: {
    changeDate() {
      this.$forceUpdate()
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'code', text: '编号', dictCode: '' })
      this.superFieldList = fieldList
    },
    searchQuery() {
      if (typeof this.beforeSearch === 'function') {
        let isreturn = this.beforeSearch()
        if (!isreturn) {
          return
        }
      }
      this.loadData(1)
      // 点击查询清空列表选中行
      // https://gitee.com/jeecg/jeecg-boot/issues/I4KTU1
    },
    loadData(arg) {
      if (!this.url.list) {
        this.$message.error('请设置url.list属性!')
        return
      }
      //加载数据 若传入参数1则加载第一页的内容
      if (arg === 1) {
        this.ipagination.current = 1
      }
      let params = {
        code: this.queryParam.code,
        status: this.queryParam.status,
        createBy: this.queryParam.createBy,
        createTimeBg: this.queryParam.createTimeBg + ' 00:00:00',
        createTimeEd: this.queryParam.createTimeEd + ' 23:59:59',
      }

      console.log('this.queryParam.createTimeBg')
      console.log(this.queryParam.createTimeBg)
      console.log(this.queryParam.createTimeBg)
      this.loading = true
      getAction(this.url.materialReceiveList, params)
        .then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
            this.dataSource = res.result.records || res.result
            this.dataSourceBack = this.dataSource
            if (res.result.total) {
              this.ipagination.total = res.result.total
            } else {
              this.ipagination.total = 0
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleDetail: function (record) {
      let noticeRecord = record

      noticeRecord.id = record.noticeId
      noticeRecord.code = record.noticeCode
      this.$refs.modalForm.edit(noticeRecord)
      this.$refs.modalForm.title = '详情'
      this.$refs.modalForm.disableSubmit = true
    },
    sanitizeHTML(html) {
      // 使用合适的库来清理 HTML 内容，例如 DOMPurify
      // return DOMPurify.sanitize(html);
      const div = document.createElement('div')
      div.innerHTML = html

      // 遍历并移除可能不安全的标签或属性
      const allowedTags = ['b', 'i', 'u', 'em', 'strong', 'a', 'br']
      const elements = div.getElementsByTagName('*')

      for (let i = elements.length - 1; i >= 0; i--) {
        const el = elements[i]
        if (!allowedTags.includes(el.tagName.toLowerCase())) {
          el.parentNode.removeChild(el)
        }
      }

      return div.innerHTML
    },
  },
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>